#include <print_error.h>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
// link with -lboost_filesystem-gcc

#include <string>
#include <algorithm>
#include <fstream>
#include <stdexcept>
#include "open_stream_name_with_substitutions.h"
using std::ofstream;
using std::string;
using std::map;
using std::vector;
using std::exception;
using std::logic_error;
using std::runtime_error;
using boost::filesystem::path;
using boost::filesystem::extension;
using boost::filesystem::basename;
using boost::algorithm::replace_all;


void open_stream_with_substitutions(ofstream&					ostrm,
									string&						new_file_name,
									const string&				format_str,
									const string& 				file_name,
									const map<string, string>&	custom_replacements)
{
	new_file_name =get_file_name_substitutions(	format_str, file_name, custom_replacements);

	// try open
	ostrm.open(new_file_name.c_str());
	// is open?
	if (!ostrm.good())
		throw std::runtime_error("Could not open the file (" + new_file_name + ").");
}


string get_file_name_substitutions(	string		 				new_file_name,
									const string& 				file_name,
									const map<string, string>&	custom_replacements)
{
	// file must have name
	if (!file_name.length())
		throw std::logic_error("No file name specified in get_file_name_substitutions().\n");

	// must have path
	if (!new_file_name.length())
		throw std::logic_error("No output file path specified in get_file_name_substitutions().\n");


	string path_part;
	string ext_part;
	string file_part;

	// try open
	try
	{
		path orig_path(file_name);
		ext_part	= extension(orig_path);
		file_part	= basename(orig_path);

		// non-path always end in /
		path_part = orig_path.branch_path().string();
		if (path_part.length() && path_part[path_part.length() - 1] != '/')
			path_part += '/';
	}
	catch (exception const & e)
	{
		throw std::runtime_error("This is not a valid file:\n[" + file_name + "]");
	}

	replace_all(new_file_name, string("[FILENAME]"), 	file_part);
	replace_all(new_file_name, string("[EXT]"), 		ext_part);
	replace_all(new_file_name, string("[PATH]"), 		path_part);
	BOOST_FOREACH(auto& replace_pair, custom_replacements) 
		replace_all(new_file_name, replace_pair.first, replace_pair.second);
	return 	new_file_name;
}


